package admin.controllers;

import helpers.GoogleStorageHelper;
import helpers.IdUniqueHelper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import admin.forms.ApplicationTemplateForm;
import admin.models.ApplicationModel;
import admin.models.ApplicationTemplateModel;
import admin.models.TemplateModel;
import entities.Application;
import entities.ApplicationTemplate;
import entities.Template;

@SuppressWarnings("serial")
public class ApplicationTemplateAddServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/admin/application/list");
			return ;
		}
		
		ApplicationModel appModel = ApplicationModel.getInstance();
		Application app = appModel.get(id);
		
		if (app == null) {
			response.sendRedirect("/admin/application/list");
			return ;
		}
		
		TemplateModel templateModel = TemplateModel.getInstance();
		List<Template> templates = templateModel.listAll();
		
		ApplicationTemplateModel appTemplateModel = ApplicationTemplateModel.getInstance();
		ApplicationTemplate template = new ApplicationTemplate();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("template", template);
		request.setAttribute("templates", templates);
		request.setAttribute("app", app);
		try {
			request.getRequestDispatcher("/admin/pages/application_template_add_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/admin/application/list");
			return ;
		}
		
		ApplicationModel appModel = ApplicationModel.getInstance();
		Application app = appModel.get(id);
		
		if (app == null) {
			response.sendRedirect("/admin/application/list");
			return ;
		}
		
		request.setAttribute("appId", id);
		
		ApplicationTemplateModel appTemplateModel = ApplicationTemplateModel.getInstance();
		ApplicationTemplate template = new ApplicationTemplate();
		
		TreeMap<String, Object> form = ApplicationTemplateForm.checkValid(request, template);
		template = (ApplicationTemplate) form.get("template");
		check = (TreeMap<String, String>) form.get("checkValid");
		
		if (check.size() == 0) {
			template = getContentTemplate(template, template.getId());
			
			appTemplateModel.insert(app.getId(), template);
			
			request.setAttribute("success", "Creat new template " + template.getId() + " success");
			
			template = new ApplicationTemplate();
		}
		
		TemplateModel templateModel = TemplateModel.getInstance();
		List<Template> templates = templateModel.listAll();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("template", template);
		request.setAttribute("templates", templates);
		request.setAttribute("app", app);
		try {
			request.getRequestDispatcher("/admin/pages/application_template_add_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	private ApplicationTemplate getContentTemplate(ApplicationTemplate appTemplate, String templateId) {
		TemplateModel templateModel = TemplateModel.getInstance();
		Template template = templateModel.get(templateId);
		
		try {
			/*
			 * Get list file by request to python application
			 */
			
			String[] splitFileName = GoogleStorageHelper.getListFile(templateId);
			/*
			 * read all files and compress
			 */
			for (String filename : splitFileName) {
				String content = "";
				if (filename.contains("home.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setHome(content);
				} 
				
				if (filename.contains("header.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setHeader(content);
				}
				
				if (filename.contains("footer.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setFooter(content);
				}
				
				if (filename.contains("layouts.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setLayout(content);
				}
				
				if (filename.contains("archives.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setArchives(content);
				}
				
				if (filename.contains("article_info.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setArticleInfo(content);
				}
				
				if (filename.contains("author_articles.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setAuthorArticle(content);
				}
				
				if (filename.contains("authors.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setAuthors(content);
				}
				
				if (filename.contains("category.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setCategory(content);
				}
				
				if (filename.contains("tag.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setTag(content);
				}
				
				if (filename.contains("contact.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setContact(content);
				}
				
				if (filename.contains("rewriter.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setRewriter(content);
				}
				
				if (filename.contains("static.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setStaticPage(content);
				}
				
				if (filename.contains("submit_article.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setSubmitArticle(content);
				}
				
				if (filename.contains("gsearch.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setSearch(content);
				}
				
				if (filename.contains("library.php")) {
					content = GoogleStorageHelper.readFileGoogleStorage(filename);
					appTemplate.setLibrary(content);
				}
			}
			
			appTemplate.setBaseUrl(template.getBaseUrl());
			
		} catch (Exception e) {
			e.printStackTrace(System.err);
			System.out.println(
							"Error when trying to download template. Please try again later !");
		}
		
		
		return appTemplate;
	}
}
